package com.xyz.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.xyz.controller.FileController;
import com.xyz.entity.mapper.SystemFileMapper;
import com.xyz.entity.pojo.SystemFile;
import com.xyz.entity.pojo.SystemFileExample;
import com.xyz.service.FileService;
import com.xyz.util.dto.DataResult;
import com.xyz.util.dto.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class FileServiceImpl implements FileService {

    @Autowired
    private SystemFileMapper fileMapper;

    @Override
    public List<String> saveFile(Map<String, String> map) throws Exception {
        List<String> codeList = new ArrayList<>();
        for (String filePath : map.keySet()) {
            String code = SecureUtil.md5(SecureUtil.md5(filePath) + filePath);
            SystemFile newSf = new SystemFile();
            newSf.setFileCode(code);
            newSf.setFileName(map.get(filePath));
            newSf.setFileUrl(filePath);
            fileMapper.insert(newSf);
            codeList.add(code);
        }
        return codeList;
    }

    @Override
    public SystemFile readFile(String fileCode) throws Exception {
        SystemFileExample sfExample = new SystemFileExample();
        sfExample.createCriteria().andFileCodeEqualTo(fileCode);
        List<SystemFile> sfList = fileMapper.selectByExample(sfExample);
        return sfList.size() == 1 ? sfList.get(0) : null;
    }

    @Override
    public DataResult deleteFile(LoginInfo li, String fileCode) throws Exception {
        SystemFile sf = fileMapper.selectByPrimaryKey(fileCode);
        if (sf == null) {
            return DataResult.build9100();
        }
        fileMapper.deleteByPrimaryKey(fileCode);
        if (sf.getFileUrl() == null) { // 文件码错误或路径不存在
            return DataResult.build9100();
        }
        File file = new File(FileController.FILE_PATH + sf.getFileUrl()); // 获取文件绝对路径，创建File对象
        boolean isDelete = file.delete();
        if (isDelete) {
            return DataResult.build9100();
        } else {
            return DataResult.build9200("文件删除失败");
        }
    }

}
